package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.CheckItemMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exception.CheckItemException;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @version V1.0
 * @author: ljx
 * @date: 2020/01/09 20:45
 * @description:
 */
@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemMapper checkItemMapper;

    @Override
    public void add(CheckItem checkItem) {
        checkItemMapper.add(checkItem);
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public PageResult findPage(QueryPageBean pageBean) {
        //使用分页查询插件，传入页码数和每页条数，返回一个封装了总记录数，总页数等page对象
        Page page = PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
        //调用dao层传入查询条件，获取根据条件查询到的checkItem的list集合
        List<CheckItem> items = checkItemMapper.findPage(pageBean.getQueryString());
        //封装返回结果集，传入总记录数和list集合
        PageResult pageResult = new PageResult(page.getTotal(), items);
        pageResult.setResult(new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS));
        return pageResult;
    }

    @Override
    public Result update(CheckItem item) {
        int i = checkItemMapper.update(item);
        return i == 0 ? new Result(false, MessageConstant.EDIT_CHECKITEM_FAIL) : new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
    }

    @Override
    public Result delete(String id) {
        //    先到t_checkitem_checkgrop表中查询，待删除的检查项是否存在外键引用
        Integer count = checkItemMapper.findCountById(id);
        if (count > 0) {
            throw new CheckItemException();
        } else {
            checkItemMapper.delete(id);
            return new Result(true,MessageConstant.DELETE_CHECKITEM_SUCCESS);
        }
    }

    @Override
    public List<CheckItem> findAllCheckItem() {
        return checkItemMapper.findAllCheckItem();
    }
}
